#!/usr/bin/env node
/*
 * 生成 ICO 并为 exe 设置图标
 * 用法：node tools/make_icon_and_set.js <exePath> <jpgPath> <outIcoPath>
 */
const fs = require('fs');
const path = require('path');

async function main() {
  const [exePath, jpgPath, outIcoPath] = process.argv.slice(2);
  if (!exePath || !jpgPath || !outIcoPath) {
    console.error('用法：node tools/make_icon_and_set.js <exePath> <jpgPath> <outIcoPath>');
    process.exit(1);
  }

  const absExe = path.resolve(exePath);
  const absJpg = path.resolve(jpgPath);
  const absIco = path.resolve(outIcoPath);

  if (!fs.existsSync(absExe)) {
    console.error('找不到 exe：', absExe);
    process.exit(0);
  }
  if (!fs.existsSync(absJpg)) {
    console.error('找不到图片：', absJpg);
    process.exit(0);
  }

  let Jimp, pngToIco, rcedit;
  try { Jimp = require('jimp'); } catch (e) {
    console.error('缺少依赖 jimp，请先安装：npm install jimp');
    process.exit(0);
  }
  try { pngToIco = require('png-to-ico'); } catch (e) {
    console.error('缺少依赖 png-to-ico，请先安装：npm install png-to-ico');
    process.exit(0);
  }
  try { rcedit = require('rcedit'); } catch (e) {
    console.error('缺少依赖 rcedit，请先安装：npm install rcedit');
    process.exit(0);
  }

  try {
    // 兼容不同版本的 Jimp 导入方式
    const JimpClass = Jimp.Jimp || Jimp.default || Jimp;
    const base = await JimpClass.read(absJpg);
    const sizes = [16, 24, 32, 48, 64, 128, 256];
    const pngBuffers = [];
    for (const s of sizes) {
      const buf = await base.clone().resize(s, s).getBufferAsync('image/png');
      pngBuffers.push(buf);
    }
    const icoBuffer = await pngToIco(pngBuffers);
    fs.mkdirSync(path.dirname(absIco), { recursive: true });
    fs.writeFileSync(absIco, icoBuffer);
    console.log('已生成 ICO：', absIco);

    await new Promise((resolve, reject) => {
      rcedit(absExe, { icon: absIco }, (err) => err ? reject(err) : resolve());
    });
    console.log('已设置 exe 图标：', absExe);
  } catch (err) {
    console.error('设置图标失败（跳过）：', err.message);
    process.exit(0);
  }
}

main();


